<?php

namespace common\models\datas;

use Yii;
use common\components\behaviors\UpdateCacheBehavior;
use yii\helpers\ArrayHelper;
use common\components\helpers\Fun;
use yii\helpers\Url;
use common\components\extenders\MenuManage;

/**
 * This is the model class for table "{{%product_type}}".
 *
 * @property integer $id
 * @property string $name
 * @property string $description
 * @property integer $enabled
 */
class ProductType extends \common\components\bases\BaseModel
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%product_type}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'description'], 'required'],
            [['enabled'], 'integer'],
            [['name'], 'string', 'max' => 50],
            [['description'], 'string', 'max' => 200]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => \Yii::t('frontend', '自动编号'),
            'name' => \Yii::t('frontend', '类型名称'),
            'description' => \Yii::t('frontend', '类型描述'),
            'enabled' => \Yii::t('frontend', '是否开启'),
        ];
    }

    public function extraFields()
    {
        return [
            'backend_operate' => function () {
                return (new MenuManage(MenuManage::RECORD_ITEM_TOOLBAR, $this->attributes))->create();
            },
            'attr_tree_url' => function () {
                $menu_cache = Fun::cache('menu_main_cache');
                if (isset($menu_cache[80])) {
                    return Url::to([$menu_cache[80]['c'] . '/' . $menu_cache[80]['a'], 'type_id' => $this->id]);
                }
            }
        ];
    }

    public function fields()
    {
        $fields = parent::fields();
        $fields['enabled'] = function () {
            switch ($this->enabled) {
                case 0:
                    return \Yii::t('common', '未开启');
                case 1:
                    return \Yii::t('common', '开启');
            }
        };
        return $fields;
    }


    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), [
            [
                'class' => UpdateCacheBehavior::className(),
                'cacheName' => 'category',

            ],
        ]);
    }
}
